﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

namespace Haidou.Wpf.UI.Windows
{
	public partial class ShutdownTimerPanel : UserControl
	{
		private int _shutdownSeconds = 0;
		public event RoutedEventHandler BackClicked;

		public ShutdownTimerPanel()
		{
			InitializeComponent();
		}

		private void RadioButton_Checked_1(object sender, RoutedEventArgs e) => _shutdownSeconds = 30 * 60; // 半小时
		private void RadioButton_Checked_2(object sender, RoutedEventArgs e) => _shutdownSeconds = 60 * 60; // 1小时
		private void RadioButton_Checked_3(object sender, RoutedEventArgs e) => _shutdownSeconds = 120 * 60; // 2小时
		private void RadioButton_Checked_4(object sender, RoutedEventArgs e) => _shutdownSeconds = 180 * 60; // 3小时

		private void BtnStart_Click(object sender, RoutedEventArgs e)
		{
			int waitSeconds = _shutdownSeconds;
			string custom = CustomTimeBox.Text?.Trim();
			if (!string.IsNullOrEmpty(custom))
			{
				if (int.TryParse(custom, out int min) && min > 0)
				{
					waitSeconds = min * 60;
				}
				else
				{
					MessageBox.Show("输入的不是有效的数字", "提示");
					return;
				}
			}
			if (waitSeconds <= 0)
			{
				MessageBox.Show("请选择或输入关机时间", "提示");
				return;
			}
			ShutdownPC(false, (uint)waitSeconds);
			MessageBox.Show($"已设置 {waitSeconds / 60} 分钟后关机", "提示");
		}

		private void BtnCancel_Click(object sender, RoutedEventArgs e)
		{
			ShutdownPC(true, 0);
			MessageBox.Show("已取消定时关机", "提示");
		}

		private void BtnBack_Click(object sender, RoutedEventArgs e)
		{
			BackClicked?.Invoke(this, e);
		}

		private static void ShutdownPC(bool isCancel, uint interval)
		{
			Process proc = new();
			proc.StartInfo.FileName = "cmd.exe";
			proc.StartInfo.UseShellExecute = false;
			proc.StartInfo.RedirectStandardError = true;
			proc.StartInfo.RedirectStandardInput = true;
			proc.StartInfo.RedirectStandardOutput = true;
			proc.StartInfo.CreateNoWindow = true;
			proc.Start();
			string commandLine = isCancel ? @"shutdown /a" : @"shutdown /s /t " + interval.ToString();
			proc.StandardInput.WriteLine(commandLine);
		}
	}
}